/*
 * @Author: czy
 * @Date: 2021-05-21 19:50:31
 * @LastEditTime: 2021-05-21 21:46:10
 */
#include "string.h"
#include "vsprintf.h"

#include "api/system.h"

static char environ[10][ENV_SIZE] = {"history=", "command="};
static int envnum = 2;

/**
 * @description: Get the environment variable.
 * @param name	Name of environment variable.
 * @param value	Value of environment variable.
 * @return 1 for found, 0 for not found.
 */
int env(const char *name, char *value)
{
	char temp[20] = "";
	sprintf(temp, "%s=", name);
	for (int i = 0; i < envnum; i++)
	{
		if (strindex(temp, environ[i]) == 0)
		{
			substring(value, environ[i], strlen((char *)name) + 1, -1);
            return 1;
		}
	}
	return 0;
}

/**
 * @description: Set the environment variable.
 * @param name	Name of environment variable.
 * @param value	Value of environment variable.
 * @return 1 for found, 0 for not found.
 */
int export(const char *name, const char *value)
{
	char temp[20] = "";
	sprintf(temp, "%s=", name);
	for (int i = 0; i < envnum; i++)
	{
		if (strindex(temp, environ[i]) == 0)
		{
			sprintf(environ[i], "%s=%s", name, value);
			return 1;
		}
	}
	sprintf(environ[envnum++], "%s=%s", name, value);
	return 0;
}

/**
 * @description: Add the environment variable.
 * @param name	Name of environment variable.
 * @param value	Value of environment variable.
 * @return 1 for found, 0 for not found.
 */
int set(const char *name, const char *value)
{
	char temp[20] = "";
	sprintf(temp, "%s=", name);
	for (int i = 0; i < envnum; i++)
	{
		if (strindex(temp, environ[i]) == 0)
		{
            if (strlen(temp) == strlen(environ[i]))
            {
                sprintf(temp, "%s", value);
            }
            else
            {
                sprintf(temp, ";%s", value);
            }
			strcat(environ[i], temp);
			return 1;
		}
	}
	return 0;
}
